<template>
  <div class="worker-node-list">
    <div v-if="showBackButton" class="header">
      <button @click="handleBack">返回</button>
      <div class="server-info">
        <span>服务器编号: {{ selectedWorkerId }}</span>
      </div>
    </div>
    
    <table>
      <thead>
        <tr>
          <th v-for="header in headers" :key="header">{{ header }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="node in nodes" :key="node.worker_id">
          <td>{{ node.worker_id }}</td>
          <td>{{ node.os_version }}</td>
          <td>{{ node.boot_time }}</td>
          <td>{{ node.available_cpu }}</td>
          <td>{{ node.available_memory }}</td>
          <td>{{ node.running_tasks }}</td>
          <td>{{ node.version }}</td>
          <td>
            <button 
              @click="showJobDetails(node.worker_id)"
              class="action-btn detail-btn"
            >
              Job详情
            </button>
            <label class="switch">
              <input 
                type="checkbox" 
                :checked="node.is_enabled" 
                @change="toggleWorkerNode(node.worker_id, $event.target.checked)"
              >
              <span class="slider round"></span>
            </label>
          </td>
        </tr>
      </tbody>
    </table>
    
    <div v-if="!showBackButton" class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">Previous</button>
      <span>Page {{ currentPage }}</span>
      <button @click="nextPage">Next</button>
    </div>
    
    <Toast v-if="showToast" :message="toastMessage" @close="showToast = false" />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { getWorkerNodes, enableWorkerNode } from '../../api/workerNodes'
import Toast from '../common/Toast.vue'

export default {
  components: { Toast },
  emits: ['show-job-details'],
  setup(props, { emit }) {
    const nodes = ref([])
    const currentPage = ref(1)
    const showToast = ref(false)
    const toastMessage = ref('')
    const selectedWorkerId = ref('')
    const showBackButton = ref(false)
    
    const headers = [
      '服务器编号', '操作系统版本', '开机时间', '可用cpu数量', 
      '可用内存数量(GB)', '进行中的任务数量', 'worker node 版本', '操作'
    ]

    const fetchNodes = async () => {
      try {
        const data = await getWorkerNodes(currentPage.value)
        nodes.value = data.nodes
      } catch (error) {
        console.error('Failed to fetch worker nodes:', error)
      }
    }

    onMounted(fetchNodes)

    const nextPage = () => {
      currentPage.value++
      fetchNodes()
    }

    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--
        fetchNodes()
      }
    }

    const showToastMessage = (message) => {
      toastMessage.value = message
      showToast.value = true
      setTimeout(() => {
        showToast.value = false
      }, 3000)
    }

    const showJobDetails = (worker_id) => {
      selectedWorkerId.value = worker_id
      showBackButton.value = true
      emit('show-job-details', worker_id)
    }

    const handleBack = () => {
      showBackButton.value = false
      emit('go-back')
    }

    const toggleWorkerNode = async (worker_id, is_enable) => {
      try {
        await enableWorkerNode(worker_id, is_enable ? 1 : 0)
        showToastMessage(`成功，这个worker已经${is_enable ? '启用' : '停用'}`)
      } catch (error) {
        console.error('Failed to toggle worker node:', error)
      }
    }

    return {
      nodes,
      headers,
      currentPage,
      showToast,
      toastMessage,
      selectedWorkerId,
      showBackButton,
      nextPage,
      prevPage,
      showJobDetails,
      handleBack,
      toggleWorkerNode
    }
  }
}
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.server-info {
  display: flex;
  gap: 20px;
}

/* Switch styles */
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
  margin-left: 10px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 34px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #42b983;
}

input:checked + .slider:before {
  transform: translateX(26px);
}

/* Table styles */
table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

button {
  padding: 5px 10px;
  cursor: pointer;
}
</style>
